package com.example.demo.service;

import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author haitao
 * @date 2021/7/25 8:28 下午
 */
@Service
public class RabbitSender {

    @Resource
    private RabbitTemplate rabbitTemplate;


    public void sendObject(String message,String exchange,String routingKey) {
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println(correlationData);
            if (!ack) {
                System.out.println("发送到exchange失败，原因：" + cause);
            }
        });

        rabbitTemplate.setReturnsCallback(returnedMessage ->
                System.out.println("交换机无法将消息路由到队列 returnMessage：" + returnedMessage)
        );

        // 消息的唯一性是通过CorrelationData的id来确定的,做可靠性消息投递需要用到
        // 工作中不能中UUID，重复率极低，但是不严谨
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());

       Message msg = MessageBuilder.withBody(message.getBytes(StandardCharsets.UTF_8))
                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("UTF-8")
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                .build();

        rabbitTemplate.convertAndSend(exchange, routingKey, msg, correlationData);
    }
}
